package com.hebeiwangxiaozhang.oauth2.filter;

import com.hebeiwangxiaozhang.oauth2.pojo.OauthClient;
import com.hebeiwangxiaozhang.oauth2.repo.ClientRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@WebFilter(filterName = "OauthFilter")
public class OauthFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(OauthFilter.class);

    @Autowired
    private ClientRepository clientRepository;

    @Override
    public void init(FilterConfig filterConfig){
        //进行一些初始化操作，比如filter中需要使用一些对象，可以在此进行对象的初始化操作
        //此处无需使用
        logger.info("Init {} to handle the oauth authorize validate!", filterConfig.getFilterName());
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURI();
        if(url.equals("/oauth/authorize")) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if(!parameterMap.containsKey("redirect_url")) {
                returnJson(servletResponse, "redirect_url is a required parameter!");
                return;
            }
            OauthClient client = clientRepository.queryByClientId(parameterMap.get("client_id")[0]);
            String redirectUrl = parameterMap.get("redirect_url")[0];
            if(!redirectUrl.equals(client.getRedirectUrl())) {
                returnJson(servletResponse, "redirect_url is not the same with the register one!*");
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    private void returnJson(ServletResponse response, String json) {
        ServletOutputStream outputStream = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            outputStream = response.getOutputStream();
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            logger.error("response error", e);
        } finally {
            if (outputStream != null)
//                writer.close();
            {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    @Override
    public void destroy() {
        //服务退出销毁filter，无需额外处理。
    }
}